<template>
  <div class="main-con flex1 vbox">
    <div class="search-con">
      <el-form :model="searchParam" :inline="true" label-width="105px">
        <el-form-item label prop="commodityCode">
          <el-input
            v-model.trim="searchParam.commodityCode"
            @keyup.enter.native="search"
            placeholder="输入订单编号查询(多个按逗号分隔)"
          ></el-input>
        </el-form-item>
        <el-form-item label prop="afterCode">
          <el-input
            v-model.trim="searchParam.afterCode"
            @keyup.enter.native="search"
            placeholder="输入转运单号查询(多个按逗号分隔)"
          ></el-input>
        </el-form-item>
        <el-form-item label prop="consumerCode">
          <el-select
            clearable
            filterable
            :filter-method="filterMethod"
            v-model="searchParam.consumerCode"
            placeholder="请选择客户"
          >
            <el-option
              v-for="item in consumerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label prop="state">
          <base-select v-model="searchParam.state" dictCode="order_state" holder="请选择订单状态"></base-select>
        </el-form-item>
        <el-form-item label prop="prdCode">
          <el-select clearable filterable v-model="searchParam.prdCode" placeholder="请选择产品查询">
            <el-option
              v-for="item in prds"
              :key="item.id"
              :label="item.prdName"
              :value="item.prdCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="90px" prop="destination">
          <base-select
            type="custom"
            code="htk-admin"
            @keyup.enter.native="search"
            v-model.trim="searchParam.destination"
            url="country/selectCountries"
            holder="请选择路向（目的地）"
          ></base-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchTimes"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-popover placement="right" width="600" trigger="click" style="margin:0 10px;">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="问题状态" prop="rmkState">
                <el-select clearable filterable v-model="searchParam.rmkState" placeholder="问题状态">
                  <el-option
                    v-for="item in rmkStates"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收件人手机号" prop="recipientsPhone">
                <el-input
                  v-model.trim="searchParam.recipientsPhone"
                  @keyup.enter.native="search"
                  placeholder="输入收件人手机号查询"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发件人手机号" prop="senderPhone">
                <el-input
                  v-model.trim="searchParam.senderPhone"
                  @keyup.enter.native="search"
                  placeholder="输入发件人手机号查询"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收件人姓名" prop="recipientsName">
                <el-input
                  v-model.trim="searchParam.recipientsName"
                  @keyup.enter.native="search"
                  placeholder="输入收件人姓名查询"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发件人姓名" prop="senderName">
                <el-input
                  v-model.trim="searchParam.senderName"
                  @keyup.enter.native="search"
                  placeholder="输入发件人姓名查询"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-button type="primary" icon="el-icon-edit" slot="reference">更多条件</el-button>
        </el-popover>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="vbox flex1">
      <div class="toolbar">
        <el-button type="primary" v-auth="'add'" icon="el-icon-plus" @click="addOrder">添加订单</el-button>
        <el-button
          type="success"
          v-auth="'import'"
          icon="el-icon-upload"
          @click="openImportDialog"
        >导入订单</el-button>
        <el-button
          :loading="exporting"
          type="success"
          v-auth="'export'"
          icon="el-icon-download"
          @click="exportOrder"
        >{{exporting ? "正在导出" : "导出订单"}}</el-button>
        <el-button
          :disabled="selectOrders.length==0"
          type="primary"
          v-auth="'batchPrint'"
          icon="el-icon-printer"
          slot="reference"
          @click="batchPrint"
        >批量打印</el-button>
        <el-button
          :disabled="selectOrders.length==0"
          type="info"
          v-auth="'batch-delete'"
          icon="el-icon-remove"
          @click="batchDelete"
        >批量删除</el-button>
        <el-popover placement="right" width="200" trigger="click" style="margin-left:10px;">
          <base-select v-model="updateStateParam.state" dictCode="order_state"></base-select>
          <el-button
            style="margin-top:12px;width:100%"
            @click="updateOrderState"
            type="primary"
            :disabled="!updateStateParam.state"
          >确认更改</el-button>
          <el-button
            :disabled="selectOrders.length==0"
            type="info"
            v-auth="'stateChange'"
            icon="el-icon-edit"
            slot="reference"
          >状态更改</el-button>
        </el-popover>
      </div>
      <base-table
        class="orderTable"
        @view-order="viewOrder"
        ref="orderTable"
        url="order/getPage"
        code="htk"
        :selection="true"
        :param="searchParam"
        :cls="columns"
        :optionBtns="optionBtns"
        @handlerOption="handlerOption"
        @selection-change="selectionChange"
        :option-width="205"
      ></base-table>
    </div>
    <el-dialog
      custom-class="customDialogClass"
      :visible.sync="showPrintDialog"
      :width="printDialgWidth"
      top="1%"
    >
      <div style="color:#000;max-height:900px;">
        <el-form>
          <ElFormItem label="选择打印机">
            <el-select v-model="printIndex">
              <el-option v-for="(p,index) in prints" :key="p" :label="p" :value="index"></el-option>
            </el-select>
            <!-- <el-button
              :disabled="printIndex<0"
              style="margin-left:10px"
              @click="print"
              icon="el-icon-printer"
              type="info"
            >打印</el-button>-->
            <!-- <el-button
              style="margin-left:10px"
              @click="downloadPrintTemplate"
              icon="el-icon-download"
              type="info"
            >查看PDF</el-button>-->
            <el-button
              style="margin-left:10px"
              @click="printImg"
              icon="el-icon-printer"
              type="info"
            >打印</el-button>
            <el-button
              style="margin-left:10px"
              @click="exportOrderPdf"
              icon="el-icon-download"
              type="info"
            >下载PDF</el-button>
            <!-- <el-switch style="margin-left:10px;" v-model="isExportPdf"></el-switch>
            <span>打印同时下载PDF</span>-->
          </ElFormItem>
        </el-form>
        <el-row>
          <ElCol
            :span="8"
            v-for="selectOrder in printOrders"
            :key="selectOrder.id"
            style="margin-top:5px;"
          >
            <print-temp
              v-if="selectOrder.prdCode != 'HTK_P0022' && selectOrder.prdCode != 'HTK_P0023'"
              :order="selectOrder"
            ></print-temp>
            <canvas
              v-if="selectOrder.prdCode == 'HTK_P0022' || selectOrder.prdCode == 'HTK_P0023'"
              :style="{width:width10cm +'px',height:height10cm+'px'}"
              :src="converPdfBase64Data(selectOrder.pdfStr,'order_'+selectOrder.id)"
              :id="'order_'+selectOrder.id"
            ></canvas>
            <!-- <xiao-bao v-if="selectOrder.prdCode == 'HTK_P0012'" :data="selectOrder"></xiao-bao>
            <da-rong
              v-if="selectOrder.prdCode == 'HTK_P0010' && selectOrder.esna && selectOrder.esna.length>0"
              :data="selectOrder"
            ></da-rong>
            <temp-owner v-if="selectOrder.prdCode == 'HTK_P0017'" :data="selectOrder"></temp-owner>-->
          </ElCol>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog title="订单导入" :visible.sync="showImportOrder" center width="30%">
      <div style="text-align:center">
        <div v-if="errorMsgs && errorMsgs.length>0" style="padding:10px 0;text-align:left">
          <div style="color:red" v-for="(msg,index) in errorMsgs" :key="index">{{msg}}</div>
        </div>
        <el-select
          clearable
          filterable
          :filter-method="filterMethod"
          style="margin-bottom:12px;width:360px"
          v-model="importParam.consumerCode"
          placeholder="请选择客户"
        >
          <el-option
            v-for="item in consumerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
          </el-option>
        </el-select>
        <div style="padding:15px 0">
          <el-radio-group v-model="importParam.type">
            <el-radio :label="2">默认</el-radio>
            <el-radio :label="1">美国小包</el-radio>
          </el-radio-group>
        </div>
        <el-upload
          accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          class="el-upload-dragger-custom"
          :on-success="importSuccess"
          :on-change="fileChange"
          ref="uploadOrder"
          :auto-upload="false"
          :data="importParam"
          drag
          action="htk/order/importOrder"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :disabled="!canupload"
          :loading="importing"
          @click="startUploadExcel"
        >立即导入</el-button>
        <el-button @click="showImportOrder = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="showTrackDialog">
      <div class="vbox" style="height:350px;">
        <base-table
          class="flex1"
          :auto-load="false"
          ref="orderTrackTable"
          :url="orderTrackQueryUrl"
          code="htk"
          :cls="trackColumns"
        ></base-table>
      </div>
    </el-dialog>
    <el-dialog center title="新增/编辑公告" :visible.sync="showAddMsgDialog" width="25%">
      <el-form ref="msgForm" :model="msg">
        <el-form-item label="标题">
          <el-input v-model="msg.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" :rows="10" v-model="msg.messageRmk" placeholder="请输入公告内容"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveMsg">保存</el-button>
        <el-button @click="showAddMsgDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <div style="display:none">
      <img
        v-for="(pdfImg,index) in pdfImgs"
        :id="'oimg_'+pdfImg.orderId"
        :key="index"
        :src="pdfImg.datauri"
        alt
      />
    </div>
  </div>
</template>

<script>
// import XiaoBao from "../print/temps/TempXiaoBao.vue";
// import DaRong from "../print/temps/TempDaRong.vue";
// import TempOwner from "../print/temps/TempOwner.vue";
import PrintTemp from "../print/PrintTemp.vue";
import html2pdf from "html2pdf-fix-jspdf";
import toPx from "unit-to-px";
export default {
  components: {
    // XiaoBao,
    // DaRong,
    // TempOwner,
    PrintTemp
  },
  data() {
    let me = this;
    return {
      printDialgWidth: "300px",
      canupload: false,
      importing: false,
      exporting: false,
      showImportOrder: false,
      showAddMsgDialog: false,
      printIndex: 0,
      searchParam: {},
      loadOrderInfo: false,
      showAddOrderDialog: false,
      showPrintDialog: false,
      showTrackDialog: false,
      trans: [],
      prints: [],
      errorMsgs: [],
      selectOrders: [],
      prds: [],
      searchTimes: [],
      orderTrackQueryUrl: "",
      updateStateParam: {
        ids: [],
        state: ""
      },
      parentConsumers: [],
      consumerOptions: [],
      importParam: {
        type: 2,
        crteMngId: me.$store.state.admin.id,
        consumerCode: ""
      },
      trackColumns: [
        {
          prop: "scanDate",
          label: "时间"
        },
        {
          prop: "scanAddr",
          label: "地点或站点"
        },
        {
          prop: "scanInfo",
          label: "讯息"
        }
      ],
      columns: [
        {
          prop: "commodityCode",
          label: "订单号/转运单号",
          custom: true,
          code: "commodityCode",
          width: 150
        },
        {
          prop: "recipientsName",
          label: "寄/收件人",
          custom: true,
          code: "recipientsName",
          width: 90
        },
        { prop: "amount", label: "数量", width: 60 },
        {
          prop: "weight",
          label: "重量/价格",
          custom: true,
          code: "weight_price",
          width: 80
        },
        // { prop: "prdName", label: "产品名称" },
        {
          prop: "destination",
          label: "始发/目的地",
          custom: true,
          code: "destination",
          width: 100
        },
        {
          prop: "recipientsAddress",
          label: "发件/收件地址",
          custom: true,
          code: "recipientsAddress"
        },
        {
          prop: "trackStrs",
          label: "轨迹跟踪"
          // formatter(row) {
          //   let trackStr = "";
          //   if (row.orderTracks && row.orderTracks.length > 0) {
          //     let item = row.orderTracks[0];
          //     trackStr += item.scanDate + " " + item.scanInfo + " \n ";
          //   } else {
          //     trackStr = "暂无";
          //   }
          //   return trackStr;
          // }
        },
        {
          prop: "state",
          label: "订单状态",
          width: 100,
          formatter(row) {
            let orderState = me.orderStates.find(item => {
              return item.value == row.state;
            });
            return !orderState ? "" : orderState.name;
          }
        },
        { prop: "creationTime", label: "创建时间", width: 180 },
        {
          prop: "rmkState",
          label: "问题",
          custom: true,
          code: "rmkState"
        }
      ],
      rmkStates: [{ value: 0, name: "正常" }, { value: 1, name: "问题" }],
      printOrder: {},
      optionBtns: [
        { text: "编辑", code: "list_edit", type: "primary" },
        { text: "打印", code: "list_print" },
        { text: "轨迹", code: "list_query_track" },
        {
          text: "推送",
          code: "list_push",
          type: "primary",
          render(row) {
            return row.verifyState == 0 && row.prdCode == "HTK_P0010";
          }
        },
        { text: "报告", code: "report_msg", type: "primary" },
        { text: "删除", code: "list_delete", type: "danger" }
      ],
      orderStates: [],
      printOrderList: [],
      printOrders: [],
      pdfImgs: [],
      msg: {
        id: "",
        type: 1,
        state: 0,
        title: "",
        messageRmk: "",
        ids: []
      },
      isExportPdf: false,
      width10cm: toPx("100mm"),
      height10cm: toPx("150mm")
    };
  },
  created() {
    this.initPrints();
    this.getPrdList();
    this.getOrderStates();
  },
  watch: {
    searchTimes(v) {
      if (v && v.length == 2) {
        this.searchParam.startTime = v[0];
        this.searchParam.endTime = v[1];
      } else {
        this.searchParam.startTime = "";
        this.searchParam.endTime = "";
      }
    }
  },
  mounted() {
    this.pdfjsLib = window["pdfjs-dist/build/pdf"];
    console.log(this.$parent);
    // this.initOrder = JSON.parse(JSON.stringify(this.$data.order));
  },
  activated() {
    this.getParentConsumers();
  },
  methods: {
    converPdfBase64Data(data64, canvasId) {
      let rawData = atob(data64);
      var loadingTask = pdfjsLib.getDocument({ data: rawData });
      loadingTask.promise.then(
        function(pdf) {
          console.log("PDF loaded");
          var pageNumber = 1;
          pdf.getPage(pageNumber).then(function(page) {
            var viewport = page.getViewport({ scale: 4 });
            var canvas = document.getElementById(canvasId);
            var context = canvas.getContext("2d");
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            var renderContext = {
              canvasContext: context,
              viewport: viewport
            };
            var renderTask = page.render(renderContext);
            renderTask.promise.then(function() {
              console.log("Page rendered");
            });
          });
        },
        function(reason) {
          // PDF loading error
          console.error(reason);
        }
      );
    },
    getParentConsumers() {
      let me = this;
      me.$http.ajax({
        url: "consumer/listChildren/" + me.$store.state.admin.orgId,
        success: res => {
          me.parentConsumers = res;
          me.consumerOptions = res;
        }
      });
    },
    filterMethod(query) {
      let me = this;
      if (!query.trim()) {
        me.consumerOptions = me.parentConsumers;
      } else {
        me.consumerOptions = me.parentConsumers.filter(consumer => {
          return (
            consumer.name.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            consumer.code.toLowerCase().indexOf(query.toLowerCase()) > -1
          );
        });
      }
    },
    openImportDialog() {
      this.showImportOrder = true;
      this.errorMsgs = [];
    },
    selectionChange(rows) {
      let me = this;
      me.selectOrders = rows;
      me.printOrderList = rows;
    },
    renderTemp(createElement, { column, $index }) {},
    batchPrint() {
      this.printDialgWidth = "1200px";
      this.printOrderList = this.$refs.orderTable.getSelections();
      this.getPrintFields();
    },
    getPrintFields() {
      let me = this;
      let ids = [];
      me.printOrderList.forEach(po => {
        ids.push(po.id);
      });
      const loading = this.$loading({
        lock: true,
        text: "加载订单打印数据...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      me.$http.ajax({
        url: "order/print",
        code: "htk",
        data: {
          orderIds: ids
        },
        success: res => {
          me.printOrders = res;
          me.showPrintDialog = true;
          loading.close();
        }
      });
    },
    print() {
      let me = this;
      if (me.printOrderList.length == 0) {
        return;
      }
      LODOP = getLodop();
      LODOP.SET_LICENSES(
        "",
        "212B9098415AD4881906E56573DB8D62",
        "C94CEE276DB2187AE6B65D56B3FC2848",
        ""
      );
      let strCenterStyle =
        "<!DOCTYPE html><body><style/>table {margin: 0 auto} table {border-collapse: collapse;} table, td, th {border: 1px solid black;}</style>";
      me.printOrderList.forEach(order => {
        LODOP.PRINT_INIT("订单打印");
        if (order.prdCode == "HTK_P0010") {
          LODOP.ADD_PRINT_HTM(
            "2mm",
            "2mm",
            "10cm",
            "18cm",
            strCenterStyle +
              document.getElementById("order_" + order.id).outerHTML
          );
          LODOP.ADD_PRINT_BARCODE(
            "0.238cm",
            "4.064cm",
            "4.773cm",
            "0.931cm",
            "EAN128A",
            order.afterCode
          );
          LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
          LODOP.ADD_PRINT_BARCODE(
            "2.54cm",
            "0.492cm",
            "4.501cm",
            "0.931cm",
            "EAN128A",
            order.afterCode
          );
          LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
          LODOP.SET_PRINT_STYLEA(0, "HtmWaitMilSecs", 1000);
        } else if (order.prdCode == "HTK_P0017") {
          LODOP.ADD_PRINT_HTM(
            "2mm",
            "2mm",
            "10cm",
            "18cm",
            strCenterStyle +
              document.getElementById("order_" + order.id).outerHTML
          );
          LODOP.ADD_PRINT_BARCODE(
            "0.238cm",
            "4.064cm",
            "4.773cm",
            "0.931cm",
            "EAN128A",
            order.afterCode
          );
          LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
          LODOP.ADD_PRINT_BARCODE(
            "2.54cm",
            "0.492cm",
            "6.501cm",
            "0.931cm",
            "EAN128A",
            order.afterCode
          );
          LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
          LODOP.SET_PRINT_STYLEA(0, "HtmWaitMilSecs", 1000);
        } else {
          LODOP.ADD_PRINT_HTM(
            "2mm",
            "2mm",
            "10cm",
            "10cm",
            strCenterStyle +
              document.getElementById("order_" + order.id).outerHTML
          ); //上下边距9mm，左右边距0mm
          LODOP.ADD_PRINT_BARCODE(
            "1.9cm",
            "1.2cm",
            "8cm",
            "0.8cm",
            "EAN128A",
            order.afterCode
          );
        }
        LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
        // LODOP.NewPage();
        LODOP.SET_PRINTER_INDEX(me.printIndex);
        LODOP.PRINT();
        // LODOP.BKIMG_PRINT();
      });
    },
    initPrints() {
      let me = this;
      let isMac = /macintosh|mac os x/i.test(navigator.userAgent);
      if (isMac) {
        return;
      }
      LODOP = getLodop();
      let printCount = LODOP.GET_PRINTER_COUNT();
      console.log(LODOP);
      for (var i = 0; i < printCount; i++) {
        me.prints.push(LODOP.GET_PRINTER_NAME(i));
      }
    },
    handlerOption(code, row) {
      if (code == "list_edit") {
        this.editOrder(row);
      } else if (code == "list_delete") {
        this.deleteOrder(row);
      } else if (code == "list_print") {
        if (
          row.prdCode == "001" ||
          row.prdCode == "005" ||
          row.prdCode == "018"
        ) {
          this.printDataZy(row);
        } else {
          this.printData(row);
        }
      } else if (code == "list_query_track") {
        this.queryTrack(row);
      } else if (code == "list_push") {
        this.pushOrder(row);
      } else if (code == "report_msg") {
        this.reportMsg(row);
      }
    },
    search() {
      this.$refs["orderTable"].initLoad();
    },
    reportMsg(row) {
      this.showAddMsgDialog = true;
      this.$nextTick(() => {
        this.$refs["msgForm"].resetFields();
        this.msg.ids = [row.id];
      });
    },
    saveMsg() {
      let me = this;
      me.$http.ajax({
        url: "order/saveOrderMessage",
        code: "htk",
        data: me.msg,
        success: res => {
          me.$message.success("保存成功");
          me.showAddMsgDialog = false;
        }
      });
    },
    prdRowClick(row) {
      this.searchParam.prdCode = row.prdCode;
      this.search();
    },
    queryTrack(row) {
      console.log(row.afterCode);
      this.orderTrackQueryUrl = "orderTrack/queryList/" + row.afterCode;
      this.showTrackDialog = true;
      this.$nextTick(() => {
        this.$refs.orderTrackTable.clearData();
        this.$refs.orderTrackTable.initLoad();
      });
    },
    pushOrder(row) {
      let me = this;
      me.$confirm("确定要推送选中行数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        me.$http.ajax({
          url: "order/pushOrderToDaRong/" + row.id,
          code: "htk",
          success(res) {
            me.$message.success("已发送推送请求");
            me.$refs["orderTable"].load();
          }
        });
      });
    },
    printDataZy(row) {
      let me = this;
      me.$http.ajax({
        url: "order/downloadTemplateByOrder",
        data: {
          orderIds: [row.id]
        },
        resType: "arraybuffer",
        code: "htk",
        success(res) {
          if (!res) {
            return;
          }
          const blob = new Blob([res], {
            type: "application/pdf;charset=utf-8"
          });
          // var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          // window.location.href = href;
          window.open(href);
        }
      });
    },
    printData(row) {
      let me = this;
      me.printDialgWidth = "540px";
      me.printOrder = Object.assign({}, row);
      me.printOrderList = [me.printOrder];
      me.getPrintFields();
      // me.$nextTick(() => {
      //   me.showPrintDialog = true;
      //   let printTemp = document.getElementById("print_" + row.commodityCode);
      //   me.$http.ajax({
      //     url: "product/getTemplateByPrdId/" + row.transportation,
      //     code: "htk",
      //     success(res) {
      //       if (res) {
      //         me.printIndex = res.printIndex;
      //       }
      //     }
      //   });
      // });
    },
    addOrder() {
      let me = this;
      me.$nextTick(() => {
        me.order = Object.assign({}, me.initOrder);
        me.$parent.addTab("NewOrder", {
          id: 999,
          name: "新建订单",
          parentId: 30,
          code: "NewOrder",
          resPath: "htk/order/NewOrder",
          extraData: me.order
        });
        me.$store.commit("setActiveTab", "NewOrder");
      });
    },
    getOrderInfoById(orderId, isView, title) {
      let me = this;
      me.$http.ajax({
        url: "order/getOrderById/" + orderId,
        code: "htk",
        success: res => {
          me.order = res;
          me.order.transportation = parseInt(me.order.transportation);
          me.$parent.addTab("NewOrder", {
            id: 999,
            name: "新建订单",
            title: title,
            parentId: 30,
            code: "NewOrder",
            resPath: "htk/order/NewOrder",
            extraData: me.order,
            isView: isView
          });
          me.$store.commit("setActiveTab", "NewOrder");
        }
      });
    },
    editOrder(row) {
      let me = this;
      me.showAddOrderDialog = true;
      me.$nextTick(() => {
        me.getOrderInfoById(row.id, false, "编辑订单");
      });
    },
    viewOrder(row) {
      this.getOrderInfoById(row.id, true, "查看订单");
    },
    batchDelete() {
      let me = this;
      let ids = [];
      me.selectOrders.forEach(order => {
        ids.push(order.id);
      });
      me.$confirm("确定要删除选中行数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        me.$http.ajax({
          url: "order/batchDelete",
          data: {
            ids: ids
          },
          code: "htk",
          success: res => {
            me.$message.success("删除成功");
            me.search();
          }
        });
      });
    },
    deleteOrder(row) {
      let me = this;
      me.$confirm("确定要删除选中行数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        me.$http.ajax({
          url: "order/batchDelete",
          data: {
            ids: [row.id]
          },
          code: "htk",
          success: res => {
            me.$message.success("删除成功");
            me.search();
          }
        });
      });
    },
    exportPrintTemplate() {
      let me = this;
      let scale = 4;
      me.printOrders.forEach(item => {
        let printhtmlId = "order_" + item.id;
        let html = document.getElementById(printhtmlId);
        let width = item.printTemp.width;
        let height = item.printTemp.height;
        if (item.prdCode == "HTK_P0022" || item.prdCode == "HTK_P0023") {
          width = 10;
          height = 15;
        }
        let result = html2pdf()
          .set({
            filename: item.afterCode + ".pdf",
            enableLinks: false,
            html2canvas: {
              scale: scale
            },
            jsPDF: {
              format: [
                parseFloat(((width / 2.54) * 72).toFixed(3)),
                parseFloat(((height / 2.54) * 72).toFixed(3))
              ]
            }
          })
          .from(html)
          .toPdf()
          .save();
      });
    },
    printImg() {
      let me = this;
      let htmls = [];
      LODOP = getLodop();
      LODOP.SET_LICENSES(
        "",
        "212B9098415AD4881906E56573DB8D62",
        "C94CEE276DB2187AE6B65D56B3FC2848",
        ""
      );
      let scale = 2;
      me.printOrders.forEach(item => {
        let printhtmlId = "order_" + item.id;
        let html = document.getElementById(printhtmlId);
        let width = item.printTemp.width;
        let height = item.printTemp.height;
        if (item.prdCode == "HTK_P0022" || item.prdCode == "HTK_P0023") {
          width = 10;
          height = 15;
          let result = html2pdf()
            .set({
              filename: item.afterCode + ".pdf",
              enableLinks: false,
              html2canvas: {
                scale: scale
              },
              image: { type: "png" },
              jsPDF: {
                format: [
                  parseFloat(((width / 2.54) * 72).toFixed(3)),
                  parseFloat(((height / 2.54) * 72).toFixed(3))
                ]
              }
            })
            .from(html)
            .outputImg("datauri")
            .then(res => {
              LODOP.PRINT_INIT("订单打印");
              LODOP.SET_PRINT_PAGESIZE(1, 1000, 1500, "");
              LODOP.ADD_PRINT_SETUP_BKIMG(res);
              LODOP.SET_SHOW_MODE("BKIMG_WIDTH", Math.ceil(width) + "cm");
              LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", Math.ceil(height) + "cm");
              LODOP.SET_SHOW_MODE("BKIMG_IN_PREVIEW", 1);
              LODOP.SET_SHOW_MODE("BKIMG_PRINT", 1);
              LODOP.SET_PRINTER_INDEX(me.printIndex);
              LODOP.PRINT();
            });
        } else {
          let leftp = "0.5mm";
          if (item.prdCode == "HTK_P0012") {
            leftp = "0mm";
          }
          LODOP.PRINT_INIT("订单打印");
          LODOP.SET_PRINT_PAGESIZE(
            1,
            Math.ceil(width) * 100,
            Math.ceil(height) * 100,
            ""
          );
          LODOP.ADD_PRINT_HTM(
            leftp,
            leftp,
            Math.ceil(width) + "cm",
            Math.ceil(height) + "cm",
            document.getElementById(printhtmlId).outerHTML
          );
          if (item.printTempFields && item.printTempFields.length > 0) {
            item.printTempFields.forEach(field => {
              if (field.type == "barcode") {
                LODOP.ADD_PRINT_BARCODE(
                  field.fieldTop,
                  field.fieldLeft,
                  field.barcodeWidth,
                  field.height,
                  "128A",
                  item.afterCode
                );
                LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
              }
            });
          }
          LODOP.SET_PRINT_STYLEA(0, "HtmWaitMilSecs", 1000);
          LODOP.SET_PRINTER_INDEX(me.printIndex);
          LODOP.PRINT();
        }
      });
    },
    downloadPrintTemplate() {
      let me = this;
      let ids = [];
      me.printOrderList.forEach(order => {
        ids.push(order.id);
      });
      me.$http.ajax({
        url: "order/exportPrintTemplate",
        data: {
          ids: ids
        },
        resType: "arraybuffer",
        code: "htk",
        success: res => {
          console.log(res);
          if (!res) {
            return;
          }
          const blob = new Blob([res], {
            type: "application/pdf;charset=utf-8"
          });
          // var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          // window.location.href = href;
          window.open(href);
          // downloadElement.download = "导出文件.xls"; //下载后文件名
          // document.body.appendChild(downloadElement);
          // downloadElement.click(); //点击下载
          // document.body.removeChild(downloadElement); //下载完成移除元素
          // window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      });
    },
    exportOrderPdf() {
      let me = this;
      let afterCodes = [];
      me.printOrders.forEach(order => {
        afterCodes.push(order.afterCode);
      });
      const loading = this.$loading({
        lock: true,
        text: "正在生成PDF，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      me.$http.ajax({
        url: "order/exportPdfByAfterCodes",
        data: afterCodes,
        code: "htk",
        resType: "arraybuffer",
        success: res => {
          loading.close();
          if (!res) {
            return;
          }
          const blob = new Blob([res], {
            type: "application/pdf;charset=utf-8"
          });
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = new Date().getTime() + "order.pdf"; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      });
    },
    startUploadExcel() {
      if (!this.importParam.consumerCode) {
        this.$message.warning("请选择客户");
        return;
      }
      this.$refs.uploadOrder.submit();
    },
    importSuccess(response, file, fileList) {
      console.log(response);
      this.importing = false;
      this.search();
      this.errorMsgs = [];
      if (response.data && response.data.length > 0) {
        this.errorMsgs = response.data;
        let index = fileList.findIndex(item => {
          return item.uid == file.uid;
        });
        fileList.splice(index, 1);
        return;
      }
      if (response.msg) {
        this.$message.success(response.msg);
      }
    },
    fileChange(file, fileList) {
      if (!fileList || fileList.length == 0) {
        this.canupload = false;
      } else {
        this.canupload = true;
      }
    },
    updateOrderState() {
      let me = this;
      me.updateStateParam.ids = [];
      me.selectOrders.forEach(item => {
        me.updateStateParam.ids.push(item.id);
      });
      me.$http.ajax({
        url: "order/updateOrderState",
        data: me.updateStateParam,
        code: "htk",
        success: res => {
          me.$message.success("更改成功");
          me.search();
          me.updateStateParam.state = "";
        }
      });
    },
    getOrderStates() {
      let me = this;
      me.$http.ajax({
        url: "sysDictData/getForSelect/order_state",
        success: res => {
          me.orderStates = res;
        }
      });
    },
    getPrdList() {
      let me = this;
      me.$http.ajax({
        url: "product/getAll",
        code: "htk",
        success: res => {
          me.prds = res;
        }
      });
    },
    exportOrder() {
      let me = this;
      if (!me.searchParam.prdCode) {
        me.$message.warning("请选择上方的【产品】后再进行导出操作");
        return;
      }
      me.$http.ajax({
        url: "order/exportOrder",
        data: me.searchParam,
        code: "htk",
        resType: "arraybuffer",
        success: res => {
          console.log(res);
          me.exporting = false;
          if (!res) {
            return;
          }
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=utf-8"
          });
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "导出文件.xls"; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      });
    }
  }
};
</script>

<style >
.el-tooltip__popper {
  position: absolute;
  border-radius: 4px;
  padding: 10px;
  z-index: 2000;
  font-size: 12px;
  line-height: 1.2;
  min-width: 10px;
  width: 250px;
  word-wrap: break-word;
  white-space: pre-line !important;
}
</style>
